clear
clear mata
clear matrix

mata:
void GMM_DLWC(todo,betas,crit,g,H)
{
	PHI=st_data(.,("phi"))
    PHI_LAG=st_data(.,("phi_lag"))
	E = st_data(.,("epsilon"))
    Z=st_data(.,("phi_lag","l_lag","l","k","m_lag","age"))
    X=st_data(.,("l","k","m","age"))
    X_lag=st_data(.,("l_lag","k_lag","m_lag","age_lag"))
    Y=st_data(.,("y"))
    C=st_data(.,("const"))
	
	
	OMEGA=PHI-X*(betas[1]^2/(1+betas[1]^2),betas[2]^2/(1+betas[2]^2),betas[3],betas[4])' 
	OMEGA_lag=PHI_LAG-X_lag*(betas[1]^2/(1+betas[1]^2),betas[2]^2/(1+betas[2]^2),betas[3],betas[4])'
	
    OMEGA_lag_pol= (C,OMEGA_lag)
	g_b = invsym(OMEGA_lag_pol'OMEGA_lag_pol)*OMEGA_lag_pol'OMEGA
	XI=OMEGA-OMEGA_lag_pol*g_b + E
	crit=(Z'XI)'(Z'XI)
}

void DLWC()
	{
initialvalue=st_data(1,("initialx","initialz","initialm","initiala"))
S=optimize_init()
optimize_init_evaluator(S, &GMM_DLWC())
optimize_init_evaluatortype(S,"d0")
optimize_init_technique(S, "nm")
optimize_init_nmsimplexdeltas(S, 0.01)
optimize_init_which(S,"min")
optimize_init_params(S,initialvalue)
p=optimize(S)
f=optimize_result_value(S)
p
f
st_matrix("beta_dlw",(p,f))
    } 
end

capture program drop dlwc	
program dlwc, rclass
preserve 
sort firm t
mata DLWC()
end
